<template>
  <PostWriter :post="post" @save="handleSave" />
</template>
<script lang="ts">
import { Post } from "@/types";
import { defineComponent } from "vue";
import { useStore } from "@/store";
import { useRouter, useRoute } from "vue-router";
import PostWriter from "./PostWriter.vue";
export default defineComponent({
  name: "EditViewer",
  emits: ["save"],
  props: {
    post: {
      type: Object as () => Post,
      required: true,
    },
  },
  components: {
    PostWriter,
  },
  async setup() {
    const route = useRoute();
    const store = useStore();
    const id = route.params.id as string;
    if (!store.getState().posts.loaded) {
      await store.fetchPosts();
    }
    const post = store.getState().posts.all[id];
    const router = useRouter();
    const handleSave = async (post: Post) => {
      // 数据存储
      await store.updatePosts(post);
      // 页面返回
      router.push("/");
    };

    return { post, handleSave };
  },
});
</script>